package cn.luckdou.system.controller.we_chat;

import java.util.List;
import java.util.Date;

import cn.luckdou.WeChat.utils.AccessTokenUtils;
import cn.luckdou.WeChat.utils.HttpUtils;
import cn.luckdou.commons.base.BaseController;
import cn.luckdou.commons.result.PageInfo;
import cn.luckdou.commons.utils.Des3Util;
import cn.luckdou.commons.utils.JsonUtils;
import cn.luckdou.system.model.we_chat.WeChat;
import cn.luckdou.system.service.we_chat.IWeChatService;
import cn.luckdou.WeChat.model.MoBanMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;

/**
 * <p>Description:管理 <／p>
 * Copyright: Copyright (c) 20017;
 * @author Dadou
 * @DateTime 2017-12-06 
 * @version 1.0
 **/
@Controller
@RequestMapping("/admin/weChat")
public class WeChatController extends BaseController {
	// log日志
	private static Logger logger = Logger.getLogger(WeChatController.class);
    
    @Autowired private IWeChatService weChatService;

	/**
	 * <p>Description: 发送消息</p>
	 * @author Dadou
	 * @DateTime 2017-12-06
	 * @version 1.0
	 * @param id
	 * @return
	 */
	@PostMapping("/sendmsg")
	@ResponseBody
	public Object sendmsg(String id) {
		WeChat weChat = weChatService.selectById(id);
		String token = AccessTokenUtils.getToken();
		String url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+ token;
		MoBanMessage moBanMessage=new MoBanMessage(weChat.getOpenId());
		{
			MoBanMessage.DataBean nameBean = new MoBanMessage.DataBean(weChat.getNikeName(),"#A73177");
			MoBanMessage.DataBean titleBean = new MoBanMessage.DataBean(weChat.getOpenId(),"#A73177");
			moBanMessage.getData().put("name",nameBean);
			moBanMessage.getData().put("title",titleBean);
		}
		try{
			String params = JsonUtils.objectToJson(moBanMessage);
			String s = HttpUtils.sendPostBuffer(url, params);
			return renderSuccess("发送成功！");
		}catch (Exception e){
			return renderError("发送失败！");
		}
	}

    /**
	 * <p>Description: 列表页面</p>
	 * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @version 1.0
     * @return
     */
    @GetMapping("/manager")
    public String manager() {
        return "admin/system/weChat/weChatList";
    }

	/**
	 * <p>Description: 列表分页</p>
	 * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @version 1.0
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public PageInfo dataGrid(WeChat weChat, Integer page, Integer rows, String sort, String order) {
        EntityWrapper<WeChat> wrapper = new EntityWrapper<WeChat>();
        wrapper.like("nike_name",weChat.getNikeName());
        weChat.setNikeName(null);
        wrapper.setEntity(weChat);
        Page<WeChat> pages = getPage(page, rows, sort, order);
        pages = weChatService.selectPage(pages,wrapper);
        return pageToPageInfo(pages);
    }
    
    /**
	 * <p>Description: 添加页面</p>
	 * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @version 1.0
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
        return "admin/system/weChat/weChatAdd";
    }
    
    /**
	 * 
	 * <p>Title: pageList</p>
	 * <p>Description: WAP调用分页列表</p>
	 * @author Dadou   
	 * @DateTime 2017-08-08
	 * @return
	 */
    @PostMapping("/pageList")
    @ResponseBody
    public Page<WeChat> pageList(WeChat weChat,@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10")  Integer rows,
			@RequestParam(defaultValue = "id") String sort,
			@RequestParam(defaultValue = "desc") String order) {
    	EntityWrapper<WeChat> wrapper = new EntityWrapper<WeChat>();
    	wrapper.setEntity(weChat);
    	Page<WeChat> pages = getPage(page, rows, sort, order);
    	pages = weChatService.selectPage(pages,wrapper);
    	return pages;
    }
    
    /**
	 * 
	 * <p>Title: list</p>
	 * <p>Description: 后台调用列表</p>
	 * @author Dadou   
	 * @DateTime 2017-08-08
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Object list(WeChat weChat) {
		EntityWrapper<WeChat> wrapper = new EntityWrapper<WeChat>();
        wrapper.setEntity(weChat);
		List<WeChat> list = weChatService.selectList(wrapper);
		return list;
	}
	
	/**
	 * 
	 * <p>Title: appList</p>
	 * <p>Description: API接口调用</p>
	 * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @param weChat
	 * @param json  
	 * @return
	 */
	@RequestMapping("/app/list")
	@ResponseBody
	public Object appList(WeChat weChat, String json) {
		if (StringUtils.isNotBlank(json)) {
			try {
				json = Des3Util.decode(json);
				json=json.replaceAll("'", "\"");
				weChat=JsonUtils.jsonToPojo(json, WeChat.class);
				EntityWrapper<WeChat> wrapper = new EntityWrapper<WeChat>();
        		wrapper.setEntity(weChat);
				List<WeChat> list = weChatService.selectList(wrapper);
				return success(list.isEmpty()?null:list);
			} catch (Exception e) {
				return error(e.getMessage());
			}
		}
		return error("参数不能为空");
		
	}
	


    /**
	 * <p>Description: 添加</p>
	 * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @version 1.0
     * @param 
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(WeChat weChat, String json) {
		if (StringUtils.isNotBlank(json)) {
			try {
				json = Des3Util.decode(json);
				json=json.replaceAll("'", "\"");
				weChat=JsonUtils.jsonToPojo(json, WeChat.class);
			} catch (Exception e) {
				return error(e.getMessage());
			}
		}
		weChat.setCreatedTime(new Date());
        boolean b = weChatService.insert(weChat);
        if (b) {
            return renderSuccess("添加成功！");
        } else {
            return renderError("添加失败！");
        }
    }

    /**
	 * <p>Description: 删除</p>
	 * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @version 1.0
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
        boolean b = weChatService.deleteById(Long.parseLong(id));
        if (b) {
            return renderSuccess("删除成功！");
        } else {
            return renderError("删除失败！");
        }
    }
    
    /**
	 * <p>Description: 批量删除</p>
	 * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @version 1.0
	 * @param ids
	 * @return
	 */
	@PostMapping("/deleteIds")
	@ResponseBody
	public Object deleteIds(String ids) {
		if (StringUtils.isNotBlank(ids)) {
			String[] split = ids.split(",");
			int num = 0;
			for (String id : split) {
				boolean b = weChatService.deleteById(Long.parseLong(id));
				if (b) {
					num++;
				}
			}
			if (num > 0) {
				return renderSuccess("删除"+num+"条记录成功！");
			} else {
				return renderError("删除失败！");
			}
		}
		return renderError("参数错误");
	}

    /**
     * 编辑
     * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @version 1.0
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, String id) {
        WeChat weChat = weChatService.selectById(id);
        model.addAttribute("weChat", weChat);
        return "admin/system/weChat/weChatEdit";
    }

    /**
     * 编辑
     * @author Dadou   
	 * @DateTime 2017-12-06 
	 * @version 1.0
     * @param 
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Object edit(WeChat weChat, String json) {
		if (StringUtils.isNotBlank(json)) {
			try {
				json = Des3Util.decode(json);
				json=json.replaceAll("'", "\"");
				weChat=JsonUtils.jsonToPojo(json, WeChat.class);
			} catch (Exception e) {
				return error(e.getMessage());
			}
		}
		weChat.setUpdatedTime(new Date());
        boolean b = weChatService.updateById(weChat);
        if (b) {
            return renderSuccess("编辑成功！");
        } else {
            return renderError("编辑失败！");
        }
    }
    
}
